<template>
  <el-dialog
    v-model="dialogVisible"
    title="📚 借阅图书"
    width="560px"
    :before-close="handleClose"
    class="borrow-dialog"
  >
    <div v-if="book" class="borrow-content">
      <div class="book-preview">
        <div class="book-cover-container">
          <el-image
            :src="book.coverUrl || '/default-book-cover.jpg'"
            :alt="book.name"
            class="book-cover"
            fit="cover"
          >
            <template #error>
              <div class="cover-placeholder">
                <el-icon><Reading /></el-icon>
              </div>
            </template>
          </el-image>
          <div class="availability-badge">
            <span class="stock-text">库存: {{ book.available }}</span>
          </div>
        </div>
        
        <div class="book-details">
          <h3 class="book-title">{{ book.name }}</h3>
          <div class="book-meta">
            <div class="meta-item">
              <span class="meta-label">👤 作者</span>
              <span class="meta-value">{{ book.author }}</span>
            </div>
            <div class="meta-item">
              <span class="meta-label">📖 ISBN</span>
              <span class="meta-value">{{ book.isbn }}</span>
            </div>
            <div class="meta-item">
              <span class="meta-label">📚 分类</span>
              <span class="meta-value">{{ book.categoryName }}</span>
            </div>
          </div>
        </div>
      </div>
      
      <el-form
        ref="borrowFormRef"
        :model="borrowForm"
        :rules="borrowRules"
        label-width="100px"
        class="borrow-form"
      >
        <el-form-item label="📅 借阅天数" prop="days">
          <el-select v-model="borrowForm.days" style="width: 100%" class="days-select">
            <el-option label="📌 7天 (短期阅读)" :value="7" />
            <el-option label="📌 14天 (推荐)" :value="14" />
            <el-option label="📌 30天 (深度学习)" :value="30" />
            <el-option label="📌 60天 (研究用途)" :value="60" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="📝 借阅备注" prop="remark">
          <el-input
            v-model="borrowForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入借阅备注，如：学习用途、研究方向等（可选）"
            maxlength="200"
            show-word-limit
            class="remark-input"
          />
        </el-form-item>
        
        <div class="borrow-tips">
          <div class="tip-item">
            <el-icon class="tip-icon"><InfoFilled /></el-icon>
            <span>请按时归还图书，逾期将影响信用记录</span>
          </div>
          <div class="tip-item">
            <el-icon class="tip-icon"><WarningFilled /></el-icon>
            <span>如需续借，请在到期前3天内申请</span>
          </div>
        </div>
      </el-form>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose" class="cancel-btn">
          取消
        </el-button>
        <el-button type="primary" :loading="loading" @click="handleConfirm" class="confirm-btn">
          <el-icon v-if="!loading"><Check /></el-icon>
          {{ loading ? '借阅中...' : '确认借阅' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Reading, InfoFilled, WarningFilled, Check } from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'
import request from '@/utils/request'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  book: {
    type: Object,
    default: null
  }
})

const emit = defineEmits(['update:visible', 'success'])

const authStore = useAuthStore()

const borrowFormRef = ref()
const loading = ref(false)

const borrowForm = reactive({
  days: 14,
  remark: ''
})

const borrowRules = {
  days: [
    { required: true, message: '请选择借阅天数', trigger: 'change' }
  ]
}

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

const resetForm = () => {
  borrowForm.days = 14
  borrowForm.remark = ''
  if (borrowFormRef.value) {
    borrowFormRef.value.clearValidate()
  }
}

const handleConfirm = async () => {
  try {
    const valid = await borrowFormRef.value.validate()
    if (!valid) return
    
    loading.value = true
    
    await request.post('/borrows/borrow', {
      userId: authStore.user.id,
      bookId: props.book.id,
      days: borrowForm.days,
      remark: borrowForm.remark
    })
    
    ElMessage.success('借阅成功')
    emit('success')
    handleClose()
  } catch (error) {
    console.error('借阅失败:', error)
    ElMessage.error(error.response?.data?.message || '借阅失败')
  } finally {
    loading.value = false
  }
}

watch(
  () => props.visible,
  (newVal) => {
    if (newVal) {
      resetForm()
    }
  }
)
</script>

<style scoped>
.borrow-content {
  padding: 20px 0;
}

.book-preview {
  display: flex;
  gap: 20px;
  margin-bottom: 32px;
  padding: 24px;
  background: linear-gradient(135deg, #f8f9ff 0%, #f0f2ff 100%);
  border-radius: 16px;
  border: 1px solid #e8ebf7;
}

.book-cover-container {
  position: relative;
  flex-shrink: 0;
}

.book-cover {
  width: 90px;
  height: 130px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}

.cover-placeholder {
  width: 90px;
  height: 130px;
  background: linear-gradient(135deg, #667eea, #764ba2);
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 28px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}

.availability-badge {
  position: absolute;
  top: -8px;
  right: -8px;
  background: linear-gradient(135deg, #4facfe, #00f2fe);
  color: white;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 11px;
  font-weight: 600;
  box-shadow: 0 2px 8px rgba(79, 172, 254, 0.4);
}

.book-details {
  flex: 1;
  min-width: 0;
}

.book-title {
  margin: 0 0 16px 0;
  font-size: 20px;
  color: #2c3e50;
  font-weight: 700;
  line-height: 1.3;
  word-break: break-word;
}

.book-meta {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.meta-label {
  font-size: 14px;
  min-width: 60px;
  font-weight: 600;
  color: #6c757d;
}

.meta-value {
  font-size: 14px;
  color: #2c3e50;
  flex: 1;
  word-break: break-word;
}

.borrow-form {
  background: white;
  padding: 24px;
  border-radius: 12px;
  border: 1px solid #e8ebf7;
}

.days-select {
  border-radius: 8px;
}

.remark-input {
  border-radius: 8px;
}

.borrow-tips {
  margin-top: 20px;
  padding: 16px;
  background: #f8f9ff;
  border-radius: 12px;
  border-left: 4px solid #667eea;
}

.tip-item {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  margin-bottom: 8px;
  font-size: 13px;
  line-height: 1.4;
}

.tip-item:last-child {
  margin-bottom: 0;
}

.tip-icon {
  color: #667eea;
  margin-top: 2px;
  flex-shrink: 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.cancel-btn {
  padding: 10px 24px;
  border-radius: 8px;
  font-weight: 500;
}

.confirm-btn {
  padding: 10px 24px;
  border-radius: 8px;
  background: linear-gradient(135deg, #667eea, #764ba2);
  border: none;
  font-weight: 600;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 6px;
}

.confirm-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(102, 126, 234, 0.4);
}

.confirm-btn:disabled {
  background: #d1d5db;
  transform: none;
  box-shadow: none;
}

/* 响应式设计 */
@media (max-width: 600px) {
  .book-preview {
    flex-direction: column;
    gap: 16px;
    padding: 20px;
  }
  
  .book-cover-container {
    align-self: center;
  }
  
  .book-meta {
    gap: 8px;
  }
  
  .meta-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
  
  .dialog-footer {
    flex-direction: column;
  }
}

/* Element Plus 样式覆盖 */
:deep(.el-dialog) {
  border-radius: 16px;
}

:deep(.el-dialog__header) {
  padding: 24px 24px 16px 24px;
  background: linear-gradient(135deg, #f8f9ff 0%, #f0f2ff 100%);
}

:deep(.el-dialog__title) {
  font-size: 20px;
  font-weight: 700;
  color: #2c3e50;
}

:deep(.el-dialog__body) {
  padding: 0 24px;
}

:deep(.el-dialog__footer) {
  padding: 16px 24px 24px 24px;
  background: #f8f9ff;
}

:deep(.el-form-item__label) {
  font-weight: 600;
  color: #2c3e50;
}

:deep(.el-select .el-input__inner) {
  border-radius: 8px;
}

:deep(.el-textarea__inner) {
  border-radius: 8px;
  font-family: inherit;
}
</style> 